import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '@/store'
Vue.use(VueRouter)


let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;
VueRouter.prototype.push = function(location,resolve,reject){
    if (resolve && reject) {
        originPush.call(this, location, resolve, reject);
   } else {
   //第二种情况：外部在使用push方法的时候没有传递成功与失败的回调函数
        originPush.call(this, location, () => { }, () => { });
   }
}

VueRouter.prototype.replace = function(location,resolve,reject){
    (resolve && reject) ? originReplace.call(this,location,resolve,reject):originReplace.call(this,location,()=>{},()=>{});
   }
const router =new VueRouter({
    routes,
    scrollBehavior (to, from, savedPosition) {
        return { x: 0, y: 0 }
      }
      

})

router.beforeEach(async (to, from, next) => {
    
    let token = store.state.user.token
    let name = store.state.user.userInfo.name
    //证明已经登录 ，拿到了服务器返回的token 
    if(token){
        if(to.path=='/login'){
            next('/home')
            // 用户登录了 且去得不是login分支
        }else{
            //用户登录了 且去的不是login分支 还有用户信息
            if(name){
                //想去哪去哪
                next()
            }else{
                //代表用户登录了 没有用户信息
                try {
                    await store.dispatch('getUserInfo')
                    next()
                } catch (error) {
                    //token过期失效了 清除本地token 
                    await store.dispatch('getlogout')
                    //清除本地数据之后 让用户回到登录页重新登录 。获取新的token
                    next('/login')
                }
            }
        }
    }   else{
        //用户未登录  想去哪去哪
        let topath = to.path;
        if(topath.indexOf('trade')!=-1||topath.indexOf('pay')!=-1||topath.indexOf('center')!=-1){
            next('/login?redirect='+topath)
        }else{
            //去的并非这些路由 放行
               next() 

        }
        
    }
  })

export default router;